package org.hscoder.springboot.elastic.repository;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.hscoder.springboot.elastic.domain.EsBook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

public class EsBookRepositoryImpl implements EsBookRepositoryCustom{

    @Autowired
    private ElasticsearchTemplate template;

    @Override
    public Page<EsBook> search(String type, String author, String title, List<String> tags, Pageable pageable) {

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if(!StringUtils.isEmpty(type)){
            boolQueryBuilder.must(QueryBuilders.termQuery("type", type));
        }

        if(!StringUtils.isEmpty(author)){
            boolQueryBuilder.must(QueryBuilders.termQuery("author", author));
        }

        if(!StringUtils.isEmpty(title)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", title));
        }

        if(!CollectionUtils.isEmpty(tags)){
            boolQueryBuilder.must(QueryBuilders.termsQuery("tags", tags.toArray()));
        }

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder).withPageable(pageable).build();
        return template.queryForPage(searchQuery, EsBook.class);
    }
}
